﻿(function ($) {
	$.smarlyText = function (el, options) {
		var base = this;
		base.$el = $(el);
		base.el = el;

		base.$el.data("smarlyText", base);


		base.init = function () {
			base.options = $.extend({}, $.smarlyText.defaultOptions, options);

			base.$addButtons = [
				{
					addButton: $('#' + base.options.NoteAddButtonId).click(base.onAddButtonClick),
					addPluses: base.addNotePluses
				},
				{
					addButton: $('#' + base.options.BookmarkCheckBox).click(base.onAddButtonClick),
					addPluses: base.addBookmarkPluses
				},
				{
					addButton: $('#' + base.options.ShareCheckBox).click(base.onAddButtonClick),
					addPluses: base.addSharePluses
				}
			];

			base.$addButtons.forEach(function (obj) {
				obj.addButton.removeClass('active');
			});

/*
			base.$BookmarkCheckBox = $('#' + base.options.BookmarkCheckBox);
			base.$NoteAddButtonId = $('#' + base.options.NoteAddButtonId);
			base.$ShareCheckBox = $('#' + base.options.ShareCheckBox);

			base.$BookmarkCheckBox.attr('checked', false);
			base.$NoteAddButtonId.attr('checked', false);
			base.$ShareCheckBox.attr('checked', false);
*/

/*
			base.$BookmarkCheckBox.change(base.onAddButtonClick);
			base.$NoteAddButtonId.change(base.onAddButtonClick);
			base.$ShareCheckBox.change(base.onAddButtonClick);
*/
		};

		base.onAddButtonClick = function () {
			if (!$(this).hasClass('active')) {
				base.updateButtons($(this)).addPluses();
			} else {
				base.removePluses();
			}
		};

		base.$currentAddButton = null;

		base.addNotePluses = function () {
			$('[id^="' + base.options.TextIdPrefix + '"]', base.$el).after(function (index, html) {
				var id = $(this).attr('id').substring(base.options.TextIdPrefix.length);
				var $parent = $(this).parent();
				if ($parent.hasClass('add-plus-link')) {
				} else {
					$(this).wrap('<div class="add-plus-link" />');
				}

				return $('<a/>')
					.addClass('plus')
					.attr('val', id)
					.click(function (e) {
						e.preventDefault();
						var $textBlock = $($('[id="' + base.options.TextIdPrefix + $(this).attr('val') + '"]'), $(this).parent());
						base.removePluses();

						var ticks = ticksNow();
						var $note = $('<div />')
							.addClass('content-note')
							.append(
									$('<textarea rows="5"/>')
									.addClass('span12')
									.attr('placeholder', 'Добавьте вашу заметку, сохранение происходит автоматически каждые ' + base.options.NoteAutosaveSeconds + ' секунд')
									.attr('textId', id)
									.attr('noteId', ticks)
									.attr('new', true)
									.attr('id', base.options.NoteIdPrefix + ticks)
									.keyup(base.OnNoteKeyUp)
							)
							.append($('<div/>').addClass('wrapper').append($('<a class="share">Поделиться заметкой</a>')).append($('<a class="clear">Удалить заметку</a>')));
						$textBlock.after($note);
						$('textarea', $note).focus();

					});
			});
		};

		base.OnNoteKeyUp = function (obj) {
			var $ta = $(obj.target);
			var noteId = $ta.attr('noteId');
			var textId = $ta.attr('textId');

			if (notesChanges[noteId] == null)
				notesChanges[noteId] = {};

			notesChanges[noteId]['saveState'] = -1;

			var $saveInfo = $('span.saveinfo', $ta.parent());
			if ($saveInfo.length == 0) {
				$saveInfo = $('<span />').addClass('saveinfo').addClass('right');
				$('div.wrapper', $ta.parent()).append($saveInfo);
			}

			$saveInfo.text('* Были внесены изменения');

			$ta.unbind('keyup', base.OnNoteKeyUp);
			setTimeout(function () {
				notesChanges[noteId]['saveState'] = 0;
				$ta.keyup(base.OnNoteKeyUp);
				$.ajax({
					type: 'POST',
					url: base.options.NoteUrl,
					data: {
						NoteId: noteId,
						TextId: textId,
						Value: $ta.val()
					},
					dataType: 'json',
					success: function (data) {
						if (data.errors == null || data.errors.length == 0) {
							if (data.NoteId != noteId) {
								notesChanges[data.NoteId] = {};
								notesChanges[data.NoteId]['saveState'] = notesChanges[noteId]['saveState'];
								$ta.attr('id', base.options.NoteIdPrefix + data.NoteId).attr('noteId', data.NoteId).attr('new', false);
								noteId = data.NoteId;
							}

							switch (notesChanges[noteId]['saveState']) {
								case -1:
									$saveInfo.html('* Были внесены изменения ' + $('<span>').addClass('green-color').text('Сохранено: ' + base.nowToString()).wrap('<div/>').parent().html());
									break;
								case 0:
									notesChanges[noteId]['saveState'] = 1;
									$saveInfo.html($('<span>').addClass('green-color').text('Сохранено: ' + base.nowToString()));
									break;
								default:
									break;
							}
						} else {
							/*
														$.each(data.errors, function () {
															base.addRemoteRule($form, this.element, href + '_' + this.element, this.errorMessage, [$('[name="' + this.element + '"]', $form).val(), 'red']);
														});
														base.options.onError(data, $form, base);
							*/
						}
					}
				});
			}, 1000 * base.options.NoteAutosaveSeconds);
		};

		function ticksNow() {
			return (((new Date()).getTime() * 10000) + 621355968000000000);
		}

		var notesChanges = {};

		base.nowToString = function () {
			var now = new Date();
			var local = 'ru';
			var result = $.datepicker.formatDate('d-M-yy', now,
				{
					dayNamesShort: $.datepicker.regional[local].dayNamesShort,
					dayNames: $.datepicker.regional[local].dayNames,
					monthNamesShort: $.datepicker.regional[local].monthNamesShort,
					monthNames: $.datepicker.regional[local].monthNames
				});
			result += ' ' + now.getHours() + ':' + now.getMinutes();
			return result;
		};

		base.addBookmarkPluses = function () {
			$('[id^="' + base.options.TextIdPrefix + '"]:not(.important)', base.$el)
/*
				.filter(function () {
					return !$(this).parent().hasClass('important');
				})
*/
				.after(function (index, html) {
					var id = $(this).attr('id').substring(base.options.TextIdPrefix.length);
					var $parent = $(this).parent();
					if ($parent.hasClass('add-plus-link')) {
					} else {
						$(this).wrap('<div class="add-plus-link" />');
					}

					return $('<a/>')
						.addClass('plus')
						.attr('val', id)
						.click(function (e) {
							e.preventDefault();

							var textId = $(this).attr('val');
							var $textBlock = $($('#' + base.options.TextIdPrefix + textId), $(this).parent());
							base.removePluses();

							$textBlock.addClass('bookmark-loading');


							$.ajax({
								type: 'POST',
								url: base.options.BookmarkUrl,
								data: {
									TextId: textId,
									Title: strip($textBlock.text())
								},
								dataType: 'json',
								success: function (data) {
									if (data.errors == null || data.errors.length == 0) {
										$textBlock.removeClass('bookmark-loading').addClass('bookmark');
									} else {
										/*
																	$.each(data.errors, function () {
																		base.addRemoteRule($form, this.element, href + '_' + this.element, this.errorMessage, [$('[name="' + this.element + '"]', $form).val(), 'red']);
																	});
																	base.options.onError(data, $form, base);
										*/
									}
								}
							});

						});
				});
		};

		base.addSharePluses = function () {
			base.shareItems = {};
			
			$('[id^="' + base.options.TextIdPrefix + '"]:not([open="true"])', base.$el).add($('[id^="' + base.options.NoteIdPrefix + '"]:not([new=true])', base.$el).parent()/*, base.$el*/).after(function (index, html) {
				var id = '-1';
				var noteId = null;

				var idAttr = $(this).attr('id');
				if (idAttr != null && idAttr.match(new RegExp('^' + base.options.TextIdPrefix))) {
					id = $(this).attr('id').substring(base.options.TextIdPrefix.length);
				} else {
					var $noteTa = $('textarea', $(this));
					if ($noteTa.length == 1) {
						id = $noteTa.attr('textid');
						noteId = $noteTa.attr('noteid');
					} else {
						return $();
					}
				}

				//var id = $(this).attr('id').substring(base.options.TextIdPrefix.length);
				var $parent = $(this).parent();
				if ($parent.hasClass('add-plus-link')) {
				} else {
					$(this).wrap('<div class="add-plus-link" />');
				}
				
				var plus = $('<a/>')
					.addClass('plus')
					.attr('val', id);
				
				if (noteId != null) {
					plus.attr('note', noteId);
				}

				plus.click(function (e) {
						e.preventDefault();
						var $textBlock = $($('[id="' + base.options.TextIdPrefix + $(this).attr('val') + '"]'), $(this).parent());
						
						if (!addShareItem($(this).attr('val'), $(this).attr('note'))) {

							var sharedItems = [];

							var title = '';

							for (var key in base.shareItems) {
								var nid = base.shareItems[key].TextId;
								title += $('#' + base.options.TextIdPrefix + nid).text() + ' ';
								if (base.shareItems[key].NoteId != null) {
									for(var nk in base.shareItems[key].NoteId) {
										title += $('#' + base.options.NoteIdPrefix + nk).val() + ' ';
									}
								}
								sharedItems.push(base.shareItems[key]);
							}

							base.removePluses();

							$.ajax({
								type: 'POST',
								url: base.options.ShareUrl,
								dataType: "json",
								data: JSON.stringify({
									model: {
										Title: strip(title),
										ShareItems: sharedItems
									}
								}),
								contentType: "application/json; charset=utf-8",
								traditional: true,
								success: function (data) {
									if (data.errors == null || data.errors.length == 0) {
									} else {
										/*
											$.each(data.errors, function () {
												base.addRemoteRule($form, this.element, href + '_' + this.element, this.errorMessage, [$('[name="' + this.element + '"]', $form).val(), 'red']);
											});
											base.options.onError(data, $form, base);
										*/
									}
								},
								error: function (a, b, c) {
									alert('A problem ocurred');
								}
							});

						}
				});

				return plus;
			});
		};

		function strip(html) {
			var tmp = document.createElement("DIV");
			tmp.innerHTML = html;
			return tmp.textContent || tmp.innerText;
		}

		function addShareItem(textId, noteId) {

			var order = $('#' + base.options.TextIdPrefix + textId).attr('order');

			if (base.shareItems[order] == null) {
				base.shareItems[order] = { t: 'sdf'};
			}

			base.shareItems[order].TextId = parseInt(textId);
			
			var pluses = $('a.plus[val="' + textId + '"]:not([note])', base.$el);
			
			if (noteId != null) {
				if (base.shareItems[order].NoteId == null) {
					base.shareItems[order].NoteId = [];
				}
				base.shareItems[order].NoteId.push(parseInt(noteId));
				pluses = pluses.add($('[note="' + noteId + '"]', base.$el));
			}

			pluses.unbind('click').unwrap().remove();


			return Object.size(base.shareItems) < base.options.ShareTextCount;
		}
		
		Object.size = function (obj) {
			var size = 0, key;
			for (key in obj) {
				if (obj.hasOwnProperty(key)) size++;
			}
			return size;
		};

		base.shareItems = { };

		base.removePluses = function (except) {
			base.shareItems = {};

			$.each(base.$addButtons, function () {
				if (except == null || this.addButton[0] != except[0]) {
					this.addButton.removeClass('active');
				}
			});

			$('a.plus', base.$el).unbind('click').unwrap().remove();
		};

		base.updateButtons = function (addButton) {
			var currentObject = null;
			base.$currentAddButton = addButton;
			base.removePluses(addButton);
			$.each(base.$addButtons, function () {
				if (this.addButton[0] == base.$currentAddButton[0]) {
					currentObject = this;
				}
			});

			return currentObject;
		};

		base.init();
	};

	$.smarlyText.defaultOptions = {
		NoteAddButtonId: 'add-note',
		NoteUrl: '',
		NoteAutosaveSeconds: 3,
		BookmarkCheckBox: 'add-bookmark',
		BookmarkUrl: '',
		ShareCheckBox: 'add-share',
		ShareUrl: '',
		ShareTextCount: 3,
		TextIdPrefix: '',
		NoteIdPrefix: '',
		BookmarkIdPrefix: '',
		ShareIdPrefix: ''

	};

	$.fn.smarlyText = function (options) {
		return this.each(function () {
			(new $.smarlyText(this, options));
		});
	};

})(jQuery);